package cn.tmpan.util;
/**
 * 数据缓存
 */

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class CacheUtil {
    //最长有效期 单位:分钟
    private static final long maxTime = 3l;
    //缓存大小(字节)
    private static final long maximumSize = 10000l;
    //日志
    private static Logger logger = LoggerFactory.getLogger(CacheUtil.class);

    //缓存
    private static LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder().initialCapacity(1000).maximumSize(maximumSize).expireAfterAccess(maxTime, TimeUnit.MINUTES).build(

            new CacheLoader<String, String>() {
                //默认数据加载实现，当调用get取值的时候 如果key没有对应的值，就调用这个方法进行加载！
                @Override
                public String load(String s) throws Exception {
                    return "null";
                }
            }

    );

    public static void setKey(String key, String val) {
        loadingCache.put(key, val);
    }

    public static String getKey(String key) {
        String val = null;
        try {
            val = loadingCache.get(key);
            if ("null".equals(val)) {
                return null;
            }
            return val;
        } catch (Exception e) {
            logger.error("LoadingCache get val Error", e);
        }
        return null;
    }
}
